package com.kaibes.admin.email;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.kaibes.module.email.sender.MailTemplate;
import com.kaibes.module.email.sender.MailTemplateService;
import com.kaibes.module.email.sender.SenderInfo;
import com.kaibes.web.admin.AdminController;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.thymeleaf.ThymeleafConfig;
import com.kaibes.web.thymeleaf.Variable;

@AdminController
@RequestMapping("/admin/mail")
public class MailController {

    @Autowired
    private SenderInfo senderInfo;
    @Autowired
    private MailTemplateService mailTemplateService;
    @Autowired
    private ThymeleafConfig thymeleafConfig;

    private List<Variable> variables;

    @GetMapping("/sender")
    @ApiLink("邮件设置")
    public String senderSet(Model model) {
        model.addAttribute("senderInfo", senderInfo);
        return "mail-sender";
    }

    @GetMapping("/send")
    @ApiLink("发送邮件")
    public String send(Model model) {
        if (variables == null) {
            variables = new ArrayList<>(thymeleafConfig.getBaseVariables());
        }
        model.addAttribute("variables", variables);
        return "mail-send";
    }

    @GetMapping("/template")
    @ApiLink("邮件模板")
    public String templateSet(Model model) {
        List<MailTemplate> templateList = mailTemplateService.list();
        model.addAttribute("templateList", templateList);
        return "mail-template";
    }

    @GetMapping("/template/{key}")
    @ApiLink("邮件模板编辑")
    public String templateEdit(Model model, @PathVariable String key) {
        MailTemplate template = mailTemplateService.getByKey(key);
        if (template == null) {
            template = new MailTemplate();
            template.setKey(key);
            template.setTitle("");
            template.setEmailContent("");
        }
        model.addAttribute("template", template);
        return "mail-template-edit";
    }

}
